﻿package banmuoi.servlet;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import banmuoi.entity.Category;
import banmuoi.entity.Product;
import banmuoi.util.HibernateUtil;

@WebServlet("/crudProduct.do")
public class ProductAdmin extends SecurityAction{
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String value = checkLogin(req, resp);
		if(value != null){
			if(value.equals("1") || value.equals("3")){//admin hoặc ProductManager		
				//LẤY THAM SỐ
				int categoryId = 0;
				int productId = 0;
				try {
					categoryId = Integer.valueOf(req.getParameter("categoryId"));
					productId = Integer.valueOf(req.getParameter("productId"));
				} catch (Exception e) {
					System.out.println("Cố tình request sai định dạng số trên trình duyệt. Không mần ăn gì cả");
				}
				
				Session session = HibernateUtil.openSession();
				
				//HIỆN DANH SÁCH CATEGORY
				String hql = "FROM Category";
				Query query = session.createQuery(hql);
				List<Category> entities = query.list();
				req.setAttribute("showCategory", entities);
				
				
				//REFRESH THỰC THỂ CATEGORY
				
				if(categoryId != 0){
					Category entity = (Category) session.load(Category.class, categoryId);
					req.setAttribute("entityCategory", entity);
				}
				
				//REFRESH THỰC THỂ PRODUCT
				if(productId != 0){
					Product entity = (Product) session.load(Product.class, productId);
					req.setAttribute("entityProduct", entity);
				}
				
				
				req.getRequestDispatcher("admin/ProductAdmin.jsp").forward(req, resp);
				session.close();			
			}
		}
		
		else {
			req.getRequestDispatcher("admin/Login.jsp").forward(req, resp);
		}	
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
			
			//LẤY THAM SÔ TỪ REQUEST
			//KHỞI TẠO ĐỐI TƯỢNG
			
			//MỞ SESSION VÀ TRANSACTION
			Session session = HibernateUtil.openSession();
			Transaction trans = session.beginTransaction();
			
			try {
				//THÊM
				if(req.getParameter("btnCreate") != null){	
					try {
						Product entity = (Product) newEntity(1, req);
						session.save(entity);
						
						req.setAttribute("error", "Inserted successfully !");
					} catch (Exception e) {
						req.setAttribute("error", "Error! Can not insert ! Please try again!");
					}
					
				}
				
				//CẬP NHẬT
				else if(req.getParameter("btnUpdate") != null){
					try {
						Product entity = (Product) newEntity(2, req);
						entity.setId(Integer.valueOf(req.getParameter("txtId")));	
						session.update(entity);	
						req.setAttribute("error", "Updated successfully !");
					} catch (Exception e) {
						req.setAttribute("error", "Error! Can not update! Check and try again!");
					}
					
				}
				
				//XÓA
				else if(req.getParameter("btnDelete") != null){
					Product entity = new Product();
					try {
						entity.setId(Integer.valueOf(req.getParameter("txtId")));
						session.delete(entity);
						req.setAttribute("error", "Deleted successfully !");
					} catch (Exception e) {
						req.setAttribute("error", "ProductId can't find! Please choose your product again!");
					}
				}
				
				//THỰC THI
				trans.commit();
			} catch (HibernateException e) {
				trans.rollback();
				req.setAttribute("error", e.getMessage());
				e.printStackTrace();
			}
			
	        session.close(); 
			this.doGet(req, resp);
		}
	
	static Object newEntity(int btn, HttpServletRequest req){
		//LẤY THAM SÔ
		String idP = req.getParameter("txtId");
		String nameP = req.getParameter("txtName");
		String imageP = req.getParameter("inputImg");
		String unitPriceP = req.getParameter("txtUnitPrice");
		String quantityP = req.getParameter("txtQuantity");
		String unitBriefP = req.getParameter("txtUnitBrief");
		String noteP = req.getParameter("txtNote");
		String stateP = req.getParameter("rdoState");
		String categoryIdP = req.getParameter("cboCategory");
		
		//KHỞI TẠO ĐỐI TƯỢNG
		Product entity = new Product();	
		Category cate = new Category();
		try {
			cate.setId(Integer.valueOf(categoryIdP));
			
			entity.setName(nameP);
			entity.setImage(imageP);
			entity.setUnitPrice(Double.valueOf(unitPriceP));
			entity.setQuantity(Integer.valueOf(quantityP));
			entity.setUnitBrief(unitBriefP);
			entity.setNote(noteP);
			entity.setState(Boolean.valueOf(stateP));
			entity.setCategory(cate);
			
			return entity;
		} catch (Exception e) {
			return null;
		}	
	}
		
		
}
